/*
 * @Description: 档案类型面板
 * @Author: Rfan
 * @Date: 2022-01-20 15:45:14
 * @LastEditTime: 2022-05-25 18:58:46
 */

import { ReactElement, useEffect, useMemo, useState } from 'react';
import { Avatar, Button, Card, Checkbox, Col, Form, List, Pagination, Row, Tag } from 'antd';
import classNames from 'classnames/bind';
import { fetchRolebyUserId } from '@/api/user';
import { useOrgAndUserContext } from '../contexts/OrgAndUserContext';
import PaneOperate from './PaneOperate';
import EditUserDialog from './dialogs/EditUserDialog';
import type { CheckboxChangeEvent } from 'antd/lib/checkbox';
import styles from '../styles/userPane.module.scss';

const cx = classNames.bind(styles);
const { Meta } = Card;

const UserPane = (props: any) => {
  const { data } = props;
  const {
    selectDepartment,
    selectUserIds,
    userList,
    userListLoading,
    userTotal,
    userQuery,
    setListQuery,
    changeSelectUserId,
    userTypeFilter,
    userStateFilter
  } = useOrgAndUserContext();

  // 添加用户弹窗状态
  const [editUserVisible, setEditUserVisible] = useState(false);
  // 选中的用户信息
  const [selectUserData, setSelectUserData] = useState<any>({});
  const [form] = Form.useForm();

  form.setFieldsValue({ ...data });

  useEffect(() => {
    if (JSON.stringify(selectDepartment) !== '{}') {
      setListQuery([
        { key: 'pageNo', value: 1 },
        { key: 'pageSize', value: 10 },
        {
          key: 'param',
          value: {
            departmentId: selectDepartment.id
          }
        }
      ]);
    }
  }, [selectDepartment]);

  const cardSelectChange = (evt: CheckboxChangeEvent, info: any) => {
    changeSelectUserId(evt.target.checked, info.id);
  };

  /**
   * @description: 打开编辑用户弹窗
   * @return {*}
   */
  const showAddDialog = (info: any): void => {
    fetchRolebyUserId(info.id).then((res) => {
      info.roleList = res.data.map((item: any) => item.id);
      info.repassword = info.password;
      setSelectUserData(info);
      setEditUserVisible(true);
    });
  };

  /**
   * @description: 关闭编辑用户弹窗，根据参数判断取消还是保存
   * @param {boolean} saveFlag 保存标识
   */
  const closeAddDialog = (saveFlag: boolean) => {
    if (saveFlag) {
      //
    }
    setEditUserVisible(false);
  };

  /**
   * @description: 用户列表card用户角色组件
   * @param {any} item 用户信息
   * @return {ReactElement} card title html结构
   */
  const userRoleComp = (item: any): ReactElement => {
    return (
      <div className={cx('card__user-role')}>
        <div className="user-name">{item.nickname}</div>
        <Checkbox
          checked={selectUserIds.indexOf(item.id) >= 0}
          onChange={(evt) => {
            cardSelectChange(evt, item);
          }}
        />
      </div>
    );
  };

  /**
   * @description: 用户列表card用户名组件
   * @param {any} item 用户信息
   * @return {ReactElement} card title html结构
   */
  const userNameComp = (item: any): ReactElement => {
    return (
      <div className={cx('card__user-name')}>
        <div className="user-name">
          {item.realname}（ID: {item.id}）
        </div>
        <Tag color="green">{userTypeFilter(item.userType)}</Tag>
      </div>
    );
  };

  /**
   * @description: 用户列表card用户详情组件
   * @param {any} item 用户信息
   * @return {ReactElement} card 用户详情html结构
   */
  const userDetailComp = (item: any): ReactElement => {
    return (
      <div className={cx('card__user-detail')}>
        <Row>
          <Col span={12}>移动电话：{item.mobile}</Col>
          <Col span={12}>办公电话：{item.officeTel}</Col>
        </Row>
        <Row>
          <Col span={12}>账号状态：{userStateFilter(item.isValid)}</Col>
          <Col span={12}>邮箱：{item.email}</Col>
        </Row>
        <Row>
          <Col span={24}>
            <Row wrap={false}>
              <Col flex="auto">
                <div className={cx('card__addr')}>办公地址：{item.officeAddress}</div>
              </Col>
              <Col flex="none">
                <Button
                  size="small"
                  loading={item.loading}
                  onClick={() => {
                    showAddDialog(item);
                  }}
                >
                  详情 {'>'}
                </Button>
              </Col>
            </Row>
          </Col>
        </Row>
        <Row>
          <Col span={24}>兼职用户时限至：{item.endDate}</Col>
        </Row>
      </div>
    );
  };

  const pageChange = (page: number, _pageSize: number) => {
    setListQuery([{ key: 'pageNo', value: page }]);
  };

  return (
    <div className={cx('user-pane')}>
      <PaneOperate />
      <div className={cx('container')}>
        <List
          loading={userListLoading}
          grid={{
            gutter: 16,
            xs: 1,
            sm: 1,
            md: 1,
            lg: 1,
            xl: 2,
            xxl: 2
          }}
          dataSource={userList}
          renderItem={(item) => (
            <List.Item>
              <Card cover={userRoleComp(item)} hoverable={true}>
                {/* <Skeleton avatar active> */}
                <Meta
                  avatar={
                    // <Avatar src="https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png" />
                    <Avatar src="https://placekitten.com/100/100" />
                  }
                  title={userNameComp(item)}
                  description={userDetailComp(item)}
                />
                {/* </Skeleton> */}
              </Card>
            </List.Item>
          )}
        />
        {userList.length > userQuery.pageSize && (
          <Pagination current={userQuery.pageNo || 1} total={userTotal} onChange={pageChange} />
        )}
      </div>

      {useMemo(
        () => (
          <EditUserDialog
            visible={editUserVisible}
            data={selectUserData}
            onClose={closeAddDialog}
          />
        ),
        [editUserVisible]
      )}
    </div>
  );
};

export default UserPane;
